package controllers

import (
	"blogs/models"
	"blogs/utils"
	beego "github.com/beego/beego/v2/server/web"
)

// Operations about object
type ArticleController struct {
	beego.Controller
}

// @Title Get
// @Description 通过id查询文章
// @Param	objectId		path 	string	true		"the objectid you want to get"
// @Success 200 {object} models.Object
// @Failure 403 :objectId is empty
// @router /:objectId [get]
func (o *ArticleController) Get() {
	objectId := o.Ctx.Input.Param(":objectId")

	article := []models.Article{}
	utils.DB.Where("id=?", objectId).Find(&article)
	if len(article) > 0 {
		o.Data["json"] = map[string]interface{}{
			"msg":  "查询成功",
			"data": article,
			"code": true,
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"msg":  "查询失败",
		"data": "查询失败",
		"code": false,
	}
	o.ServeJSON()
}

// @Title GetAll
// @Description 查询所有文章
// @router / [get]
func (o *ArticleController) GetAll() {

	// page 当前页
	page, _ := o.GetInt("page")
	if page == 0 {
		page = 1
	}
	// 条数
	pageSize, _ := o.GetInt("pageSize")
	if pageSize == 0 {
		pageSize = 5
	}
	// 总条数
	var total int64
	utils.DB.Table("article").Count(&total)
	// 总页数
	//count := math.Ceil(float64(total) / float64(pageSize))

	article := []models.Article{}
	utils.DB.Preload("Tag").Offset((page - 1) * pageSize).Limit(pageSize).Find(&article)

	o.Data["json"] = map[string]interface{}{
		"msg":  "查询成功",
		"data": article,
		"code": false,
		"page": map[string]interface{}{
			"page":     page,
			"pageSize": pageSize,
			"count":    total,
		},
	}
	o.ServeJSON()
}

// @Title Put
// @Description 取前10条数据
// @Success 200
// @Failure 403
// @router / [put]
func (o *ArticleController) Put() {
	article := []models.Article{}
	utils.DB.Limit(9).Find(&article)
	o.Data["json"] = map[string]interface{}{
		"msg":  "查询成功",
		"data": article,
		"code": true,
	}
	o.ServeJSON()
}
